<template>
  <div class="panel-tab__content">
    <el-table :data="magicApiConfigList" size="small" border>
      <el-table-column label="序号" width="50px" type="index" />
      <el-table-column label="事件类型" min-width="40px"
                       :formatter="(row) =>
                         (props.type === 'Process')?ProcessInstanceEventType[row.event]:(props.type=== 'UserTask'?TaskEventType[row.event]:row.event)"
      />
      <el-table-column
          label="接口地址"
          min-width="100px"
          show-overflow-tooltip
          prop="fullDir"
      />
      <el-table-column label="操作" width="100px">
        <template #default="scope">
          <el-button size="small" link @click="openMagicApiConfigForm(scope.row, scope.$index)"
          >编辑</el-button
          >
          <el-divider direction="vertical" />
          <el-button size="small" link style="color: #ff4d4f" @click="removeMagicApiConfig(scope.$index)"
          >移除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="element-drawer__button">
      <XButton
          type="primary"
          preIcon="ep:plus"
          title="添加Magic-Api接口"
          size="small"
          @click="openMagicApiConfigForm(null)"
      />
    </div>

    <!-- 接口 编辑/创建 部分 -->
    <el-drawer
        v-model="MagicApiConfigModelVisible"
        title="MagicApi执行接口"
        :size="`${width}px`"
        append-to-body
        destroy-on-close
    >
      <el-form :model="magicApiConfigForm" label-width="96px" ref="maigicConfigFormRef">
        <el-form-item
            label="事件类型"
            prop="event"
            :rules="{ required: true, trigger: ['blur', 'change'] }"
        >
          <el-select v-model="magicApiConfigForm.event" v-if="props.type === 'Process'" >
            <el-option
                v-for="key in Object.keys(ProcessInstanceEventType)"
                :key="key"
                :label="ProcessInstanceEventType[key]"
                :value="key"
            />
          </el-select>
          <el-select v-model="magicApiConfigForm.event" v-if="props.type=== 'UserTask'" >
            <el-option
                       v-for="key in Object.keys(TaskEventType)"
                       :key="key"
                       :label="TaskEventType[key]"
                       :value="key"
            />
          </el-select>
        </el-form-item>
        <el-form-item
            label="Api接口"
            prop="magicApiId"
            :rules="{ required: true, trigger: ['change'] }"
        >
          <el-select
              ref="treeRef"
              v-model="magicApiConfigForm.magicApiId"
              :data="magicApiConfigOptions"
              filterable
              clearable
              empty-text="加载中，请稍后"
              @change="magicApiConfigSelectChange"
          >
            <el-option
                v-for="option in magicApiConfigOptions"
                :key="option.id"
                :label="option.fullDir"
                :value="option.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <el-divider />
      <p class="listener-filed__title">
        <span><Icon icon="ep:menu" />注入字段：</span>
        <XButton type="primary" @click="openMagicApiConfigFieldForm(null)" title="添加字段" />
      </p>
      <el-table
          :data="fieldsListOfMaginApiConfig"
          size="small"
          max-height="240"
          fit
          border
          style="flex: none"
      >
        <el-table-column label="序号" width="50px" type="index" />
        <el-table-column label="字段名称" min-width="100px" prop="name" />
        <el-table-column
            label="字段值"
            min-width="100px"
            show-overflow-tooltip
            :formatter="(row) => row.stringValue"
        />
        <el-table-column label="操作" width="130px">
          <template #default="scope">
            <el-button size="small" link @click="openMagicApiConfigFieldForm(scope.row, scope.$index)"
            >编辑</el-button
            >
            <el-divider direction="vertical" />
            <el-button
                size="small"
                link
                style="color: #ff4d4f"
                @click="removeMagicApiConfigField(scope.$index)"
            >移除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="element-drawer__button">
        <el-button @click="MagicApiConfigModelVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveMagicApiConfig">保 存</el-button>
      </div>
    </el-drawer>

    <!-- 注入西段 编辑/创建 部分 -->
    <el-dialog
        title="字段配置"
        v-model="magicApiConfigFieldModelVisible"
        width="600px"
        append-to-body
        destroy-on-close
    >
      <el-form
          :model="magicApiConfigFieldForm"
          label-width="96spx"
          ref="magicApiConfigFieldFormRef"
          style="height: 136px"
      >
        <el-form-item
            label="字段名称："
            prop="name"
            :rules="{ required: true, trigger: ['blur', 'change'] }"
        >
          <el-input v-model="magicApiConfigFieldForm.name" clearable />
        </el-form-item>
        <el-form-item
            label="字段值："
            prop="stringValue"
            key="field-string "
            :rules="{ required: true, trigger: ['blur', 'change'] }"
        >
          <el-input v-model="magicApiConfigFieldForm.stringValue" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" @click="magicApiConfigFieldModelVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="saveMagicApiConfigFiled">确 定</el-button>
      </template>
    </el-dialog>
  </div>

</template>
<script lang="ts" setup>
import { ElMessageBox } from 'element-plus'
import { createMagicApiConfigObject, updateElementExtensions} from '../../utils'
import {MagicApiConfigApi} from "@/api/bpm/magicApi";
import {ProcessInstanceEventType,TaskEventType} from "./utilSelf";

defineOptions({ name: 'MagicApiTaskConfig' })

const props = defineProps({
  id: String,
  type: String,
  elementType: String
})
const prefix = inject('prefix')
const width = inject('width')
const magicApiConfigList = ref<any[]>([]) // 接口配置列表
const magicApiConfigForm = ref<any>({}) // 接口配置详情表单
const MagicApiConfigModelVisible = ref(false) // 接口 编辑 侧边栏显示状态
const fieldsListOfMaginApiConfig = ref<any[]>([])
const magicApiConfigFieldForm = ref<any>({}) // 接口 注入字段 详情表单
const magicApiConfigFieldModelVisible = ref(false) // 接口 注入字段表单弹窗 显示状态
const editingMagicApiConfigIndex = ref(-1) // 接口所在下标，-1 为新增
const editingMagicApiConfigFieldIndex = ref(-1) // 字段所在下标，-1 为新增
const bpmnElement = ref()
const otherMagicApiConfigList = ref()
const bpmnElementMagicApiConfigs = ref()
const maigicConfigFormRef = ref()
const magicApiConfigFieldFormRef = ref()
const bpmnInstances = () => (window as any)?.bpmnInstances

const resetMagicApiConfigsList = () => {
  bpmnElement.value = bpmnInstances().bpmnElement
  otherMagicApiConfigList.value = []
  bpmnElementMagicApiConfigs.value =
      bpmnElement.value.businessObject?.extensionElements?.values?.filter(
          (ex) => ex.$type === `${prefix}:MagicApiConfig`
      ) ?? []
  magicApiConfigList.value = bpmnElementMagicApiConfigs.value.map((magicApiConfig) =>
      JSON.parse(JSON.stringify(magicApiConfig))
  )
}
// 打开 接口详情 侧边栏
const openMagicApiConfigForm = (magicApiConfig, index?) => {
  // debugger
  if (magicApiConfig) {
    magicApiConfigForm.value = magicApiConfig
    editingMagicApiConfigIndex.value = index
  } else {
    magicApiConfigForm.value = {}
    editingMagicApiConfigIndex.value = -1 // 标记为新增
  }
  if (magicApiConfig && magicApiConfig.fields) {
    fieldsListOfMaginApiConfig.value = magicApiConfig.fields.map((field) => ({
      ...field
    }))
  } else {
    fieldsListOfMaginApiConfig.value = []
    magicApiConfigForm.value['fields'] = []
  }
  // 打开侧边栏并清楚验证状态
  MagicApiConfigModelVisible.value = true
  nextTick(() => {
    if (maigicConfigFormRef.value) {
      maigicConfigFormRef.value.clearValidate()
    }
  })
}
// 打开接口字段编辑弹窗
const openMagicApiConfigFieldForm = (field, index?) => {
  magicApiConfigFieldForm.value = field ? JSON.parse(JSON.stringify(field)) : {}
  editingMagicApiConfigFieldIndex.value = field ? index : -1
  magicApiConfigFieldModelVisible.value = true
  nextTick(() => {
    if (magicApiConfigFieldFormRef.value) {
      magicApiConfigFieldFormRef.value.clearValidate()
    }
  })
}
// 保存接口注入字段
const saveMagicApiConfigFiled = async () => {
  // debugger
  let validateStatus = await magicApiConfigFieldFormRef.value.validate()
  if (!validateStatus) return // 验证不通过直接返回
  if (editingMagicApiConfigFieldIndex.value === -1) {
    fieldsListOfMaginApiConfig.value.push(magicApiConfigFieldForm.value)
    magicApiConfigForm.value.fields.push(magicApiConfigFieldForm.value)
  } else {
    fieldsListOfMaginApiConfig.value.splice(editingMagicApiConfigFieldIndex.value, 1, magicApiConfigFieldForm.value)
    magicApiConfigForm.value.fields.splice(editingMagicApiConfigFieldIndex.value, 1, magicApiConfigFieldForm.value)
  }
  magicApiConfigFieldModelVisible.value = false
  nextTick(() => {
    magicApiConfigFieldForm.value = {}
  })
}
// 移除接口字段
const removeMagicApiConfigField = (index) => {
  // debugger
  ElMessageBox.confirm('确认移除该字段吗？', '提示', {
    confirmButtonText: '确 认',
    cancelButtonText: '取 消'
  })
      .then(() => {
        fieldsListOfMaginApiConfig.value.splice(index, 1)
        magicApiConfigForm.value.fields.splice(index, 1)
      })
      .catch(() => console.info('操作取消'))
}
// 移除接口器
const removeMagicApiConfig = (index) => {
  ElMessageBox.confirm('确认移除该接口吗？', '提示', {
    confirmButtonText: '确 认',
    cancelButtonText: '取 消'
  })
      .then(() => {
        bpmnElementMagicApiConfigs.value.splice(index, 1)
        magicApiConfigList.value.splice(index, 1)
        updateElementExtensions(
            bpmnElement.value,
            otherMagicApiConfigList.value.concat(bpmnElementMagicApiConfigs.value)
        )
      })
      .catch(() => console.info('操作取消'))
}
// 保存接口器配置
const saveMagicApiConfig = async () => {
  // debugger
  let validateStatus = await maigicConfigFormRef.value.validate()
  if (!validateStatus) return // 验证不通过直接返回
  const magicApiConfigObject = createMagicApiConfigObject(magicApiConfigForm.value,  prefix)
  if (editingMagicApiConfigIndex.value === -1) {
    bpmnElementMagicApiConfigs.value.push(magicApiConfigObject)
    magicApiConfigList.value.push(magicApiConfigForm.value)
  } else {
    bpmnElementMagicApiConfigs.value.splice(editingMagicApiConfigIndex.value, 1, magicApiConfigObject)
    magicApiConfigList.value.splice(editingMagicApiConfigIndex.value, 1, magicApiConfigForm.value)
  }
  // 保存其他配置
  otherMagicApiConfigList.value =
      bpmnElement.value.businessObject?.extensionElements?.values?.filter(
          (ex) => ex.$type !== `${prefix}:MagicApiConfig`
      ) ?? []
  updateElementExtensions(
      bpmnElement.value,
      otherMagicApiConfigList.value.concat(bpmnElementMagicApiConfigs.value)
  )
  // 4. 隐藏侧边栏
  MagicApiConfigModelVisible.value = false
  magicApiConfigForm.value = {}
}

const magicApiConfigOptions = ref()

const getmagicApiTreeList = async () => {
  magicApiConfigOptions.value = await MagicApiConfigApi.getMagicApiConfigList()
}
const magicApiConfigSelectChange = async (value: any) => {
  magicApiConfigOptions.value.forEach((magicApiConfig, i) => {
    if(value == magicApiConfig.id){
      magicApiConfigForm.value.magicApiId = magicApiConfig.id ;
      magicApiConfigForm.value.fullPath = magicApiConfig.fullPath ;
      magicApiConfigForm.value.fullDir = magicApiConfig.fullDir ;
      magicApiConfigForm.value.method = magicApiConfig.method ;
    }

  });
  console.log("magicApiConfigForm",magicApiConfigForm.value);
}


watch(
    () => props.id,
    (val) => {
      val &&
      val.length &&
      nextTick(() => {
        resetMagicApiConfigsList();
        getmagicApiTreeList();
      })
    },
    { immediate: true }
)
</script>
